package com.itheima.esdemo;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

//创建和删除索引库
public class EsDemo01 {

    private RestHighLevelClient restHighLevelClient;

    @Before
    public void init(){
        restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(
                        //要连接的es地址
                        new HttpHost("192.168.200.150",9200,"http")));
    }

    @After
    public void close() throws IOException {
        restHighLevelClient.close();
    }


    //创建索引库
    @Test
    public void createIndex() throws IOException {
        //1.创建对应的请求对象
        CreateIndexRequest request = new CreateIndexRequest("user");
        //设置setting
        request.settings(
                Settings.builder().put("number_of_shards","1")
                                    .put("number_of_replicas","1")
        );
        //设置mapping   参数1 描述mapping的json字符串   参数2 字符串的类型
        request.mapping("{\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"long\"\n" +
                "      },\n" +
                "      \"name\":{\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"age\":{\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"gender\":{\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"note\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"ik_max_word\"\n" +
                "      }\n" +
                "    }\n" +
                "  }", XContentType.JSON);
        //2.调用客户端执行对应的请求
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        //3.解析执行结果
        System.out.println(createIndexResponse.isAcknowledged());
    }


    //删除索引库
    @Test
    public void deleteIndex() throws IOException {
        //1.创建对应的请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("user");
        //2.调用客户端执行对应的请求
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        //3.解析执行结果
        System.out.println(delete.isAcknowledged());
    }
}
